{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 当鼠标按下时变为True\n",
    "drawing = False\n",
    "# 如果mode为true绘制矩形,按下'm'变成绘制曲线\n",
    "mode = True\n",
    "ix,iy = -1,-1\n",
    "\n",
    "# 创建回调函数\n",
    "def draw_interaction(event,x,y,flags,param):\n",
    "    global ix,iy,drawing,mode\n",
    "    if event == cv2.EVENT_LBUTTONDOWN:\n",
    "        drawing = True\n",
    "        ix,iy = x,y\n",
    "    # 当鼠标左键按下并移动时绘制图形，event可以查看移动，flag查看是否按下\n",
    "    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:\n",
    "        if drawing == True:\n",
    "            if mode == True:\n",
    "                cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)\n",
    "            else:\n",
    "                # 绘制圆圈，小圆点连在一起就成了线，3代表了笔画的粗细\n",
    "                cv2.circle(img,(x,y),3,(0,0,255),-1)\n",
    "        # 当鼠标松开停止绘画\n",
    "        elif event == cv2.EVENT_LBUTTONUP:\n",
    "            drawing == False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "img = np.zeros((512,512,3),np.uint8)\n",
    "cv2.namedWindow('draw')\n",
    "cv2.setMouseCallback('draw',draw_interaction)\n",
    "while True:\n",
    "    cv2.imshow('draw',img)\n",
    "    k = cv2.waitKey(1) & 0xFF\n",
    "    if k == ord('m'):\n",
    "        mode = not mode\n",
    "    elif k == ord('q'):\n",
    "        break\n",
    "\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
